/**
 * Express Web框架的应用模块
 * 1.导入所需模块
 * 2.导入路由模块
 * 3.应用层中间件
 * 4.定义路由
 * 5.导出Express应用实例
 */

// 1.导入所需模块

//导入Express模块
var express = require('express');
//导入Node.js的path模块
var path = require('path');
//导入Express的Cookie模块
var cookieParser = require('cookie-parser');
//导入日志模块
var logger = require('morgan');

// 导入Session模块
const session = require("express-session");
// 导入Session存储支持模块SQLite
const SQLiteStore = require("connect-sqlite3")(session);

//导入Swagger-ui-express模块
const swaggerUi = require('swagger-ui-express');
//导入Swagger-jsdoc模块
const swaggerJsdoc = require("swagger-jsdoc");
//导入初始化数据库中间件
const initSqliteDB = require("./controller/init");

// 2.导入路由模块
//导入默认路由
var indexRouter = require('./routes/index');
//导入用户路由
var usersRouter = require('./routes/users');
//导入课程路由
var courseRouter = require('./routes/courses');
//导入订单路由
var orderRouter = require('./routes/orders');
//导入评论路由
var commentsRouter = require('./routes/comments');

//生成应用实例“app”
var app = express();

// 3.应用层中间件
//开发日志
app.use(logger('dev'));
//JSON解析
app.use(express.json());
//URL编码
app.use(express.urlencoded({ extended: false }));
//Cookie
app.use(cookieParser());
//静态资源
app.use(express.static(path.join(__dirname, 'public')));

// 中间件： Swagger
const options = {
    definition: {
        openapi: "3.0.0",
        info: {
            titile: "在线课程接口",
            version: "1.0.0",
        },
    },
    apis: [path.join(__dirname, "./routes/*.js")],
};

const openapiSpecification = swaggerJsdoc(options);
app.use("/dev-api", swaggerUi.serve, swaggerUi.setup(openapiSpecification));

//中间件：数据库初始化
app.use(initSqliteDB());

/**
 * Express中的Session支持
 * 1. npm install express-sesion connect-sqlite3
 * 2. 导入模块
 * 3. 使用Session中间件
 * 4. Session存储：SQLiteStore
 */

app.use(
    session({
        secret: "sdfsdfsf@#@$234", //session的salt
        resave: false, //session工作方式：session是否重新保存
        saveUninitialized: false, //session工作方式：未初始化的session是否保存
        cookie: { maxAge: 7 * 24 * 60 * 60 * 1000 }, // sessionID在客户端cookie中保存1周
        store: new SQLiteStore({
            dir: "./data",
            db: "OnlineCourse.db",
        }),
    })
);


// 4.定义路由
//默认路由 -> /
app.use('/', indexRouter);
//用户路由 -> /users
app.use('/users', usersRouter);
//课程路由 -> /courses
app.use('/courses', courseRouter);
//订单路由 -> /orders
app.use('/orders', orderRouter);
//评论路由 -> /comments
app.use('/comments', commentsRouter);

// 5.导出Express应用实例
module.exports = app;
